package goodstemplatelogic

import (
	"common/comHttp"
	"common/dao/model"
	"common/utils"
	"context"
	"errors"
	"fmt"
	"github.com/jinzhu/copier"
	"gorm.io/gorm"
	"service/internal/svc"
	"service/pb"
	"strings"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateByCodeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}
type resp struct {
	Data struct {
		GoodsName string `json:"goodsName"`
		Barcode   string `json:"barcode"`
		Price     string `json:"price"`
		Brand     string `json:"brand"`
		Supplier  string `json:"supplier"`
		Standard  string `json:"standard"`
	} `json:"data"`
}

func NewCreateByCodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateByCodeLogic {
	return &CreateByCodeLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateByCodeLogic) CreateByCode(in *pb.CodeResp) (*pb.Emp, error) {
	// todo: add your logic here and delete this line
	if in.Barcodes == "" {
		return nil, errors.New("barcodes is null")
	}
	slice := strings.Split(in.Barcodes, ",")
	if len(slice) == 0 {
		return nil, errors.New("barcodes is xxx,xxx")
	}
	ApiGoods := l.svcCtx.Config.ApiGoods
	ls := make([]model.GoodsTemplate, 0)
	for index, code := range slice {
		if code == "" {
			continue
		}
		if index >= 1 {
			//fmt.Println("睡觉")
			time.Sleep(time.Millisecond * 1500)
		}
		var (
			goods  = model.GoodsTemplate{}
			goods1 = model.GoodsTemplate{}
		)
		s := fmt.Sprintf("%s?barcode=%s&app_id=%s&app_secret=%s", ApiGoods.Url, code, ApiGoods.AppId, ApiGoods.AppSecret)
		request, err := comHttp.Request[resp](s, comHttp.Get, goods)
		if err != nil {
			fmt.Println(err)
			continue
		}
		if request.Data.Barcode == "" {
			continue
		}
		err = copier.CopyWithOption(&goods, request.Data, copier.Option{IgnoreEmpty: true})
		if err != nil {
			fmt.Println(err)
			continue
		}
		db := l.svcCtx.DB.Table(model.TableNameGoodsTemplate)
		err = db.Transaction(func(tx *gorm.DB) error {
			if err := tx.Where("barcode = ?", goods.Barcode).Where("is_del = ?", 0).Find(&goods1).Error; err != nil {
				return nil
			}
			return nil
		})
		if err != nil {
			fmt.Println(err)
		}
		if goods1.UUID == "" && goods1.ID == 0 {
			goods.UUID = utils.GetUuid()
			t := time.Now()
			goods.CreateTime = &t
		} else {
			goods.UUID = goods1.UUID
			goods.ID = goods1.ID
			goods.CreateTime = goods1.CreateTime
		}
		ls = append(ls, goods)

	}
	if len(ls) == 0 {
		return nil, errors.New("未查询到相关商品")
	}
	db := l.svcCtx.DB.Table(model.TableNameGoodsTemplate)
	err := db.Transaction(func(tx *gorm.DB) error {
		if err := tx.Save(&ls).Error; err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return &pb.Emp{}, nil
}
